import { integerToAlphabet } from '@/utils/exampleTag'

const romanKeys = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM',
  '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC',
  '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']
// 阿拉伯数字转罗马数字
export const integerToRoman = (num) => {
  if (typeof num !== 'number')
    return ''

  let digits = String(+num).split(''),
    romanNum = '',
    i = 3
  while (i--)
    romanNum = (romanKeys[+digits.pop() + (i * 10)] || '') + romanNum
  return Array(+digits.join('') + 1).join('M') + romanNum
}

function getLevelClassName(level) {
  const _level = Number(level)
  switch(_level) {
    case 2:
      return 'num'
    case 3:
      return 'roman'
    case 4:
      return 'num2'
    case 1:
    default:
      return 'lower'
  }
}

// 自动刷新列项编号
export const resetItemListSiblingsNumber = (node, editor, dataLang) => {  
  function walk(next) {
    if (!next) return
    if (next.classList.contains('item_list') && next.dataset.lang === dataLang) {
      let level = parseInt(next.getAttribute('data-level'))
      // 如果因为删除列项导致越级了，需要订正
      const parentLevel = parseInt(next.previousElementSibling?.dataset.level || 0)
      if (parentLevel && (level - parentLevel) > 1) {
        level = parentLevel + 1
      }
      const number = getNumber({
        node: next, 
        classList: Array.from(next.classList), 
        level,
        dataLang
      })
      const value = getValue(level, number)
      const parentNumber = getParentNumber(next, level)
      const leveClassName = getLevelClassName(level)
      editor.dom.setAttribs(next, {
        'class': leveClassName + ' item_list ' + dataLang,
        'data-action': leveClassName,
        'data-value': value,
        'data-number': number,
        'data-level': level,
        'data-level-num': `${level > 1 ? parentNumber + '.' : ''}${number}`
      })  
      if (next.nextElementSibling) {
        walk(next.nextElementSibling)
      }
    }
  }
  if (node?.nextElementSibling) {
    walk(node.nextElementSibling)
  }
}

// 列项获取上级的编号
export const getParentNumber = (currentNode, level) => {
  if (level === 1) {
    return ''
  }
  function walk(node) {
    if (node?.dataset.type === 'item_list') {     
      const grade = parseInt(node.getAttribute('data-level'))
      if (grade < level) {
        return node.getAttribute('data-level-num')
      }
      return walk(node.previousElementSibling)
    } else if (node.textContent?.length === 0 && node.previousElementSibling?.dataset.type === 'item_list') {
      // 当前行若是空行，可设置为列项
      return walk(node.previousElementSibling)
    }
    return ''
  }
  return walk(currentNode)
}


/**
 * 获取编号，根据上一行的编号计算+1
 * @param {*} node 当前节点
 * @param {*} classList 需要匹配的class列表
 * @returns 编号 十进制数字
 */
export const getNumber = ({
  node, classList, level, dataLang
}) => {
  const prev = node?.previousElementSibling
  if (!prev || prev?.dataset?.lang !== dataLang) return 1
  const prevClassName = prev.getAttribute?.('class') || ''
  const _classMatch = classList.every(i => prevClassName.includes(i))
  if (_classMatch) {
    // 上一行和本行是同级
    const prevNumber = prev.dataset.number
    return parseInt(prevNumber) + 1
  }
  if (level > 0) {
    // 从上一行的level中读取对应编号
    const prevLevel = prev?.getAttribute?.('data-level-num')
    const prevNumber = prevLevel?.split('.')?.[level - 1]
    return prevNumber ? parseInt(prevNumber) + 1 : 1
  }
  return 1
}

export const getValue = (level, number) => {
  let dataValue = number
  if(level === 1) {
    dataValue = integerToAlphabet(number)
  } else if (level === 3) {
    dataValue = integerToRoman(number)
  }
  return dataValue
}
